package com.ciwong.epaper.modules.cordva.html;

import android.content.Intent;
import android.view.View;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.cordva.BaseHtmlActicity;
import com.ciwong.epaper.modules.cordva.SubmitEvent;
import com.ciwong.epaper.modules.epaper.bean.Answer;
import com.ciwong.epaper.modules.epaper.bean.Module;
import com.ciwong.epaper.modules.epaper.bean.ModuleContent;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.volley.BaseRequest;
import com.ciwong.mobilelib.bean.Main;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BrowserActivity;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.io.File;
import java.util.List;

/**
 * Created by young on 2017/2/27.
 * 新的听说模考学习记录页面
 */
public class NewLsWorkRcordActivity extends BaseHtmlActicity{

    private DownLoadInfo downLoadInfo;

    private Module mModule;

    private  String mTeacherComment;
    private String doWorkId;
    private String checkedResource;
    private int workState;

    private  int position=0;


    @Override
    protected void loadData() {
        //网络没有仍然能加载出来
        //super.loadData();
        Intent intent = getIntent();
        if (null != intent) {
            mModule = (Module) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ);
            downLoadInfo = (DownLoadInfo) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_DOWNLOAD_INFO);
            final Answer answer = (Answer) getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_ANSWER);
            workState=intent.getIntExtra(IntentFlag.INTENT_FLAG_WORK_STATUS,0);
            doWorkId = intent.getStringExtra(IntentFlag.INTENT_FLAG_ID);
            position = intent.getIntExtra(IntentFlag.INTENT_FLAG_POSITION , 0);
            checkedResource = intent.getStringExtra(IntentFlag.INTENT_FLAG_CHECKED_RESOURCE);
            mTeacherComment=getIntent().getStringExtra(IntentFlag.INTENT_FLAG_TEACHER_COMMENT);
            setTitleText(intent.getStringExtra(BrowserActivity.IntentString.INTENT_STRING_TITLE));
    }



        setStartURL("file://" + ESystem.getLsWorkEXPath() + File.separator + "lsResult.html");
       //setStartURL("http://192.168.18.181/ListenSpeek/h5/lsResult.html");
        loadUrl(startURL.toString());
        if (null != mTeacherComment&& mTeacherComment.length() > 0) {
            setRightBtnBG(R.mipmap.icon_teacher_comment);
            setRightBtnEnable(true);
            setRightBtnListener(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    DialogUtil.showCommentDialog(NewLsWorkRcordActivity.this,mTeacherComment);
                }
            });
        }

    }


    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }


    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    public void onEventMainThread(SubmitEvent submitEvent) {

        CWLog.d("SUBMIT", "我在EVENT。BUFS中" + submitEvent.getJson());
        final  String id = submitEvent.getId();
        final String callbackId=submitEvent.getCallbackId();
        if ("GetJsonData".equals(id)) {
           String arg=submitEvent.getJson();
            try {
                JSONObject jsonObject=new JSONObject(arg);
                if(jsonObject.has("source")){
                  int source=jsonObject.getInt("source");
                    if(source==3){
                        //请求资源
                        lookDetail(callbackId);
                    }
                }
            }catch (Exception e){
                e.getStackTrace();
            }
        }else if("GetUserInfo".equals(id)){
            try {
                String arg=submitEvent.getJson();
                JSONObject jsonObject=new JSONObject(arg);
                if(jsonObject.has("source")){
                    int source=jsonObject.getInt("source");
                    if(source==3){//听说模考学习记录
                        BaseRequest.VerifyInfo verifyInfo = BaseRequest.getVerifyInfo();
                        JSONObject temp=new JSONObject();
                        temp.put("clientId",verifyInfo.getClientId());
                        temp.put("accessToken",verifyInfo.getAccessToken());
                        temp.put("openid",verifyInfo.getOpenId());
                        temp.put("oauth_version",verifyInfo.getOauthVersion());
                        temp.put("scope",verifyInfo.getScope());
                        temp.put("clientip",verifyInfo.getClientIp());
                        temp.put("termtype",verifyInfo.getTermType());
                        temp.put("brandId",EApplication.BRAND_ID);
                        temp.put("doWorkId",doWorkId);
                        temp.put("checkResouresIds",checkedResource);
                        UserInfoBase userInfo = EApplication.getInstance().getUserInfoBase();
                        if(null != userInfo)
                            temp.put("userId",userInfo.getUserId());
                        sendCallBack(callbackId,temp.toString());
                    }
                }

            }catch (Exception e){
                e.getStackTrace();
            }

        }else if("GetWorkStatus".equals(id)){
            try {
            String arg=submitEvent.getJson();
            JSONObject jsonObject=new JSONObject(arg);
            if(jsonObject.has("source")){
                int source=jsonObject.getInt("source");
                if(source==3){//听说模考学习记录
                    //返回作业的批改状态
                    JSONObject jsonObject1=new JSONObject();
                    jsonObject1.put("workStatus",workState);
                    sendCallBack(callbackId,jsonObject1.toString());
                }
            }

        }catch (Exception e){
            e.getStackTrace();
        }


    }
    }

    /**
     * 查看详情
     */
    private void lookDetail(final String callbackId)
    {
        String mainPath = ESystem.getPackagesMainJsonPath(
                downLoadInfo.getBookId(), downLoadInfo.getChapterId());


        EpaperDao.getInstance().getSerializableObjects(mainPath, Main.class,
                new BaseExtCallBack(NewLsWorkRcordActivity.this, EApplication.getInstance().getUserInfoBase().getUserId()+"")
                {
                    @Override
                    public void failed(Object data)
                    {
                        super.failed(data);
                        showToastError((int) data);
                    }

                    @Override
                    public void failed(int errorCode, Object data)
                    {
                        super.failed(errorCode, data);
                    }

                    @Override
                    public void success(Object data)
                    {
                        if (isFinishing())
                        {
                            return;
                        }
                        Main main = (Main) data;
                        getCatalogueFile(main.getCatalogueFile(), callbackId);
                    }
                });
    }

    private void getCatalogueFile(String path,final String callbackId)
    {
        path = ESystem.getPackagesPath(NewLsWorkRcordActivity.this) + File.separator + path;
        EpaperDao.getInstance().getSerializableObjects(path,
                new TypeToken<List<Module>>()
                {
                }.getType(), new BaseExtCallBack(NewLsWorkRcordActivity.this,EApplication.getInstance().getUserInfoBase().getUserId()+"")
                {
                    @Override
                    public void failed(Object data)
                    {
                        showToastError((int) data);
                    }

                    @Override
                    public void failed(int errorCode, Object data)
                    {
                        super.failed(errorCode, data);
                    }

                    @Override
                    public void success(Object data)
                    {
                        if (isFinishing())
                        {
                            return;
                        }
                        List<Module> modules = (List<Module>) data;

                        ModuleContent moduleContent = getModuleByModuleId(
                                modules, callbackId);
                        if (moduleContent != null)
                        {
                            //资源JSON数据
                            String resFile = moduleContent.getResourceFile();
                            String guid = resFile.substring(
                                    resFile.lastIndexOf("/") + 1,
                                    resFile.lastIndexOf("_"));
                            //这里用答案的
                            resFile = resFile.replace(guid,
                                    "e9430760-9f2e-4256-af76-3bd8980a9de4");
                            getResult(ESystem.getPackagesJsonPath(resFile), callbackId);
                        }
                    }
                });
    }


    /**
     * 获取Module
     *
     * @param modules
     * @return
     */
    private ModuleContent getModuleByModuleId(List<Module> modules,String callbackId)
    {
        for (Module module : modules)
        {
            if (module.getModuleInfo().getModuleId() == mModule.getModuleInfo()
                    .getModuleId())
            {

                List<ModuleContent> resourceList = module.getResourceList();
                List<ModuleContent> resourceList1 = mModule.getResourceList();
                for (ModuleContent moduleContent : resourceList)
                {
                    //传进来的modleContent只是一个   不能传多个进来  做匹配作用
                    //最终使用的是资源里面的
                    int indexOf = resourceList1.indexOf(moduleContent);
                    if (indexOf >= 0)
                    {
                        return moduleContent;
                    }
                }

            }
        }
        return null;
    }

    /**
     * 获取网页展示内容
     *
     * @param path
     */
    private void getResult(final String path,final String callbackId)
    {
        EpaperDao.getInstance().getResource(path, new BaseExtCallBack(NewLsWorkRcordActivity.this,EApplication.getInstance().getUserInfoBase().getUserId()+"") {


            @Override
            public void success(final Object data) {
                if (isFinishing()) {
                    return;
                }
                //直接String
                sendCallBack(callbackId,data.toString());
            }

            @Override
            public void failed(int errorCode, Object data)
            {
                super.failed(errorCode, data);
            }

            @Override
            public void failed(Object data)
            {
                showToastError((int) data);
            }
        });

    }






}
